package com.Cychat.doctor.mapper;

import com.Cychat.commons.entity.pojo.Appointment;
import com.Cychat.commons.entity.vo.AppointmentDetailVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 预约记录Mapper（连表查询+doctorId筛选）
 */
@Mapper
public interface AppointmentMapper extends BaseMapper<Appointment> {

    /**
     * 连表查询当前医生的所有预约记录（修复别名映射）
     */
    @Select("""
        SELECT 
            -- 预约表字段（直接映射，无需别名）
            a.appointment_id, a.pet_id, a.owner_id, a.symptom, 
            a.appointment_date, a.appointment_time, a.status,
            -- 宠物表字段：别名改为 pet.xxx（对应 PetVo 字段）
            p.name AS `pet.name`, p.type AS `pet.type`, p.breed AS `pet.breed`,
            p.birthday AS `pet.birthday`, p.weight AS `pet.weight`, p.notes AS `pet.notes`,
            -- 主人表字段：别名改为 petOwner.xxx（对应 PetOwnerVo 字段）
            po.address AS `petOwner.address`, po.emergency_contact AS `petOwner.emergencyContact`,
            -- 主人用户表字段：别名改为 ownerUser.xxx（对应 UserVo 字段）
            u.nick_name AS `ownerUser.nickName`
        FROM appointment a
        LEFT JOIN pet p ON a.pet_id = p.pet_id
        LEFT JOIN pet_owner po ON a.owner_id = po.owner_id
        LEFT JOIN user u ON po.user_id = u.user_id
        WHERE a.doctor_id = #{doctorId}
        ORDER BY a.appointment_date DESC, a.appointment_time DESC
    """)
    List<AppointmentDetailVo> selectDoctorAppointmentList(@Param("doctorId") Integer doctorId);

    /**
     * 连表查询预约详情（修复别名映射）
     */
    @Select("""
        SELECT 
            a.appointment_id, a.pet_id, a.owner_id, a.symptom, 
            a.appointment_date, a.appointment_time, a.status,
            p.name AS `pet.name`, p.type AS `pet.type`, p.breed AS `pet.breed`,
            p.birthday AS `pet.birthday`, p.weight AS `pet.weight`, p.notes AS `pet.notes`,
            po.address AS `petOwner.address`, po.emergency_contact AS `petOwner.emergencyContact`,
            u.nick_name AS `ownerUser.nickName`
        FROM appointment a
        LEFT JOIN pet p ON a.pet_id = p.pet_id
        LEFT JOIN pet_owner po ON a.owner_id = po.owner_id
        LEFT JOIN user u ON po.user_id = u.user_id
        WHERE a.appointment_id = #{appointmentId} AND a.doctor_id = #{doctorId}
    """)
    AppointmentDetailVo selectDoctorAppointmentDetail(
            @Param("appointmentId") Integer appointmentId,
            @Param("doctorId") Integer doctorId
    );
}